<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片式图 -->
    <el-card>
      <!-- 搜索与添加数据 -->
      <el-row :gutter="15">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="create_time" label="创建时间"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            {{ scope.row.mg_state }}
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <el-tooltip effect="dark" placement="top" :enterable="false">
              <div slot="content">分配角色</div>
              <el-button @click="setRole(scope.row)" type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" @close="addDialogClosed" width="50%">
      <!-- 内容 -->
      <el-form :model="addForm" :rules="addFormRules" ref="ruleForm" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 内容 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editRuleForm" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="30%" @close="setRoleDialogClosed">
      <div>
        <p>当前用户： {{ userInfo.username }}</p>
        <p>当前角色： {{ userInfo.role_name }}</p>
        <p>分配角色：
          <el-select v-model="selectedRoleId">
            <el-option v-for="item in roleslist" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的
        return cb()
      } else {
        cb(new Error('请输入合法的邮箱'))
      }
    }
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}/
      if (regMobile.test(value)) {
        // 合法的
        return cb()
      } else {
        cb(new Error('请输入合法的号码'))
      }
    }
    return {
      // 获取用户列表的参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      userlist: [],
      dialogVisible: false, // 控制对话框的显示与隐藏
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3-10个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 6,
            message: '用户名的长度在3-6个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      setRoleDialogVisible:false,
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 需要被分配角色的用户信息
      userInfo:{},
      roleslist:[],
      selectedRoleId:''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      let { data: res } = await this.$axios.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      } else {
        this.userlist = res.data.users
        this.total = res.data.total
      }
      // console.log(res)
    },
    // 监听pagesize 改变的事件
    handleSizeChange(newSize) {
      //console.log(a)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值 改变的事件
    handleCurrentChange(b) {
      //console.log(b,'===');
      this.queryInfo.pagenum = b
      this.getUserList()
    },
    // 监听开关
    async userStateChanged(data) {
      // console.log(data);
      let { data: res } = await this.$axios.put(
        `users/${data.id}/state/${data.mg_state}`
      )
      if (res.meta.status !== 200) return this.$message.error('状态设置失败')
      this.$message.success(res.meta.msg)
      // console.log(res);
    },
    // 监听关闭对话框
    addDialogClosed() {
      this.$refs.ruleForm.resetFields()
    },
    // 添加新用户
    addUser() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return
        console.log(this.addForm)
        let { data: res } = await this.$axios.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) this.$message.error('用户添加失败')
        this.$message.success(res.meta.msg)
        this.dialogVisible = false
        // 重新获取数据
        this.getUserList()
      })
    },
    // 修改用户
    async showEditDialog(id) {
      this.editDialogVisible = true
      let { data: res } = await this.$axios.get(`users/${id}`)
      if (res.meta.status != 200) return this.$message.error('查询用户信息失败')
      this.editForm = res.data
      console.log(this.eidtForm)
      this.$message.success(res.meta.msg)
    },
    editDialogClosed() {
      this.$refs.editRuleForm.resetFields()
    },
    //修改用户信息提交
    editUserInfo() {
      this.$refs.editRuleForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('用户更新失败')
        } else {
          this.$message.success(res.meta.msg)
          this.editDialogVisible = false
          this.getUserList()
        }
      })
    },
    // 删除用户
    async removeUserById(id) {
      const confirmRest = await this.$confirm('永久删除该用户？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户取消删除，会报错，所以捕获一下， cancel .confirm
      if (confirmRest === 'confirm') {
        let { data: res } = await this.$axios.delete('users/' + id)
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('删除失败')
        }
        this.$message.success(res.meta.msg)
        this.getUserList()
      }
    },
    // 分配角色
    async setRole(userInfo){
      this.userInfo = userInfo;
      // 在展示对话框之前，获取所有角色的列表
      const {data:res} = await this.$axios.get('roles')
      if(res.meta.status!==200){
        return this.$message.error('获取角色列表失败!')
      }
      this.roleslist = res.data;
      this.setRoleDialogVisible = true;
    },
    // 点击按钮，分配角色
    async saveRoleInfo(){
      if(!this.selectedRoleId){
        return this.$message.error('请选择要分配的角色')
      }
      const {data:res} = await this.$axios.put(`users/${this.userInfo.id}/role`,{
        rid:this.selectedRoleId
      })
      if(res.meta.status!==200){
        return this.$message.error('更新角色失败!')
      }
      this.$message.success(res.meta.msg);
      this.getUserList();
      this.setRoleDialogVisible = false;
    },
    // 监听分配对话框的关闭事件
    setRoleDialogClosed(){
      this.userInfo = {};
      this.selectedRoleId = '';
    }
  }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 12px;
}
.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
</style>